package model

import (
	myconn "common/conn"
	"common/helper"
	"errors"
	"fmt"
	"time"

	"github.com/valyala/fasthttp"
	"github.com/valyala/fastjson"
)

func smsBuka(phone, code string) error {

	uri := fmt.Sprintf("%s?appId=%s&numbers=%s&senderId=%s&content=%s", smsConf["buka"]["api"], smsConf["buka"]["appid"], phone, "", code)
	ts := time.Now().Unix()
	sign := helper.MD5Hash(fmt.Sprintf(`%s%s%d`, smsConf["buka"]["key"], smsConf["buka"]["secret"], ts))
	header := map[string]string{
		"Content-Type": "application/json",
		"Sign":         sign,
		"Timestamp":    fmt.Sprintf(`%d`, ts),
		"Api-Key":      smsConf["buka"]["key"],
	}
	body, statusCode, _ := myconn.HttpDoTimeout(nil, "GET", uri, header, time.Duration(10)*time.Second)

	if statusCode != fasthttp.StatusOK {
		return errors.New(helper.RequestFail)
	}

	var p fastjson.Parser

	v, _ := p.ParseBytes(body)
	if string(v.GetStringBytes("status")) == "0" {
		return nil
	}

	return errors.New(helper.VerificationSendErr)
}
